<template>
  <div class="aside-container">
    <!-- Logo区域 -->
    <div class="logo-section">
      <img src="@/assets/yuanqi1.png" alt="点点开黑" class="logo-img" />
      <div class="logo-text">
        <h1>元气陪玩</h1>
        <p>享受游戏交友的乐趣</p>
      </div>
    </div>
    <!-- 导航菜单 -->
    <nav class="nav-menu">
      <ul class="menu-list">
        <li class="menu-item">
          <router-link to="/boss" class="menu-link" @click="openPlayHall()"
            >首页</router-link
          >
        </li>
        <li class="menu-item">
          <router-link to="/boss/rankingList" class="menu-link"
            >排行榜</router-link
          >
        </li>
        <li class="menu-item">
          <router-link to="/boss/myOrder" class="menu-link"
            >订单管理</router-link
          >
        </li>
      </ul>
    </nav>

    <!-- 切换到陪玩页面 -->
    <div v-if="user && user.bossName">
      <el-button type="primary" @click="openPlayHall()">大神页面</el-button>
    </div>

    <!-- 用户已登录时显示 -->
    <div v-if="user && user.bossName" class="user-info">
      <!-- 整合头像和昵称，作为一个整体触发下拉 -->
      <el-dropdown trigger="hover" @command="handleDropdownCommand">
        <div class="user-avatar-container">
          <img
            :src="user.bossAvatar || '@/assets/default-avatar.png'"
            alt="用户头像"
            class="user-avatar"
          />
          <span class="user-nickname">个人中心</span>
        </div>
        <!-- 下拉菜单内容 -->
        <el-dropdown-menu slot="dropdown">
          <!-- 用户基本信息 -->
          <div class="user-basic-info">
            <p><strong>昵称：</strong>{{ user.bossNickname }}</p>
            <p><strong>性别:</strong>{{ user.bossSex == 1 ? "女" : "男" }}</p>
            <p><strong>余额：</strong>¥{{ user.bossMoney || 0 }}</p>
          </div>

          <!-- 功能选项 -->
          <el-dropdown-item command="info">个人信息</el-dropdown-item>
          <el-dropdown-item command="giftBag">礼物背包</el-dropdown-item>
          <el-dropdown-item command="modifyPassword">修改密码</el-dropdown-item>
          <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          <el-dropdown-item command="consumptionRecord"
            >消费记录</el-dropdown-item
          >
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <!-- 用户未登录时显示 -->
    <div v-else class="user-dropdown">
      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link">
          未登录<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="login">
            <span class="dropdown-item-link">登录</span>
          </el-dropdown-item>
          <el-dropdown-item command="register">
            <span class="dropdown-item-link">注册</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <!-- 登录弹窗 -->
    <el-dialog :visible.sync="showLoginDialog" title="用户登录" width="400px">
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showLoginDialog = false">取消</el-button>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </span>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      :visible.sync="showRegisterDialog"
      title="用户注册"
      width="400px"
    >
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerForm"
        class="compact-form"
      >
        <el-form-item label="姓名" prop="name" class="compact-form-item">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName" class="compact-form-item">
          <el-input
            v-model="registerForm.nickName"
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone" class="compact-form-item">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" class="compact-form-item">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="请输入密码"
            @change="$refs.registerForm.validateField('confirmPassword')"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="确认密码"
          prop="confirmPassword"
          class="compact-form-item"
        >
          <el-input
            type="password"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address" class="compact-form-item">
          <el-select v-model="registerForm.address" placeholder="请选择地址">
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.addressName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="头像" prop="avatarUrl" class="compact-form-item">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleAvatarChange"
            :show-file-list="false"
          >
            <img
              v-if="registerForm.avatarUrl"
              :src="registerForm.avatarUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="性别" prop="gender" class="compact-form-item">
          <el-radio-group v-model="registerForm.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" class="compact-form-item">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="自我介绍"
          prop="introduction"
          class="compact-form-item"
        >
          <el-input
            type="textarea"
            v-model="registerForm.introduction"
            placeholder="请输入自我介绍"
            :rows="2"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="游戏爱好"
          prop="gameHobby"
          class="compact-form-item"
        >
          <el-input
            v-model="registerForm.gameHobby"
            placeholder="请输入游戏爱好"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showRegisterDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRegisterSubmit"
          >立即注册</el-button
        >
      </span>
    </el-dialog>

    <!-- 个人详情弹窗 -->
    <el-dialog title="个人详情" :visible.sync="infoDialogFormVisible">
      <el-form
        :model="user"
        :rules="userFormRules"
        ref="userForm"
        @validate="onFormValidate"
      >
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="handleAvatarChangeForUpdate"
          >
            <img v-if="user.bossAvatar" :src="user.bossAvatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="姓名"
          :label-width="formLabelWidth"
          prop="bossName"
        >
          <el-input v-model="user.bossName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          prop="bossNickname"
        >
          <el-input v-model="user.bossNickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="bossSex">
          <el-select
            v-model="user.bossSex"
            placeholder="请选择性别"
            :disabled="true"
          >
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="地址"
          :label-width="formLabelWidth"
          prop="addressId"
        >
          <el-select v-model="user.addressId" placeholder="居住地">
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.addressName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="邮箱"
          :label-width="formLabelWidth"
          prop="bossEmail"
        >
          <el-input v-model="user.bossEmail" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="自我介绍"
          :label-width="formLabelWidth"
          prop="bossDesc"
        >
          <el-input v-model="user.bossDesc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="游戏爱好"
          :label-width="formLabelWidth"
          prop="bossGameHobby"
        >
          <el-input v-model="user.bossGameHobby" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser()" :disabled="!formValid"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="modifyPasswordDialogVisible"
      width="400px"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        class="password-form"
      >
        <el-form-item label="原密码" prop="oldPassword" autocomplete="off">
          <el-input
            type="password"
            v-model="passwordForm.oldPassword"
            placeholder="请输入原密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" autocomplete="off">
          <el-input
            type="password"
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPassword"
          autocomplete="off"
        >
          <el-input
            type="password"
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelModifyPassword">取 消</el-button>
        <el-button type="primary" @click="submitModifyPassword"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 退出登录弹窗 -->
    <el-dialog
      title="退出登录"
      :visible.sync="logoutDialogVisible"
      width="30%"
      center
    >
      <span>请注意，即将退出登录，请确认</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="logoutDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bossLogout()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 注册成为陪玩 -->
    <el-dialog
      title="注册成为陪玩"
      :visible.sync="playmateDialogFormVisible"
      width="450px"
    >
      <el-form
        :model="playmateRegisterForm"
        :rules="playmateRegisterRules"
        ref="playmateRegisterFormRef"
        class="compact-form"
      >
        <el-form-item
          label="陪玩昵称"
          prop="playmateNickname"
          class="compact-form-item"
        >
          <el-input
            v-model="playmateRegisterForm.playmateNickname"
            placeholder="请输入陪玩昵称"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="陪玩头像"
          prop="playmateAvatarUrl"
          class="compact-form-item"
        >
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handlePlaymateAvatarChange"
            :show-file-list="false"
          >
            <img
              v-if="playmateRegisterForm.playmateAvatarUrl"
              :src="playmateRegisterForm.playmateAvatarUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item
          label="擅长游戏"
          prop="playmateGameHobby"
          class="compact-form-item"
        >
          <el-select
            v-model="playmateRegisterForm.playmateGameHobby"
            placeholder="请选择擅长游戏"
            style="width: 100%"
          >
            <el-option
              v-for="game in games"
              :key="game.id"
              :label="game.gameTypeName"
              :value="game.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="自我介绍"
          prop="playmateDesc"
          class="compact-form-item"
        >
          <el-input
            type="textarea"
            v-model="playmateRegisterForm.playmateDesc"
            placeholder="请介绍一下自己，包括游戏经验、特长等"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="playmateDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePlaymateRegisterSubmit"
          >立即注册</el-button
        >
      </span>
    </el-dialog>

    <!-- 背包弹窗 -->
    <el-dialog
      title="礼物背包"
      :visible.sync="giftBagDialogVisible"
      width="600px"
      class="gift-bag-dialog"
    >
      <div class="gift-bag-container">
        <div v-if="this.userBags.length === 0" class="empty-state">
          背包空空如也，快去获取礼物吧~
        </div>
        <div v-else class="gift-grid">
          <div v-for="bag in userBags" :key="bag.id" class="gift-item">
            <div class="gift-image-wrapper">
              <img
                :src="getGiftImage(bag.giftId)"
                :alt="getGiftName(bag.giftId)"
                class="gift-image"
              />
              <div class="gift-count">{{ bag.bagGiftNumber }}</div>
            </div>
            <div class="gift-name">{{ getGiftName(bag.giftId) }}</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="giftBagDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bossApi from "@/http/bossApi";
export default {
  name: "Aside",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value != this.passwordForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    // 在 data() 函数内添加一个新的验证函数专门用于注册表单的密码确认验证
    const validateRegisterConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value != this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      userBags: [], //当前用户背包
      gifts: [],
      tenantId: 1,
      // 在 data() 的 return 对象中添加以下内容
      playmateRegisterForm: {
        playmateNickname: "",
        playmateAvatar: null,
        playmateAvatarUrl: "",
        playmateGameHobby: "",
        playmateDesc: "",
        tenantId: 1,
        userId: "",
      },
      giftBagDialogVisible: false,
      playmateRegisterRules: {
        playmateNickname: [
          { required: true, message: "请输入陪玩昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "昵称长度应在2-20个字符之间",
            trigger: "blur",
          },
        ],
        playmateGameHobby: [
          { required: true, message: "请选择擅长游戏", trigger: "change" },
        ],
        playmateDesc: [
          { required: true, message: "请输入自我介绍", trigger: "blur" },
          { min: 10, message: "自我介绍至少10个字符", trigger: "blur" },
        ],
        playmateAvatarUrl: [
          { required: true, message: "请上传头像", trigger: "change" },
        ],
      },
      games: [],
      playmateDialogFormVisible: false,
      currtPlaymate: {},
      formValid: false,
      formLabelWidth: "120px",
      infoDialogFormVisible: false,
      logoutDialogVisible: false,
      searchText: "",
      user: {},
      showLoginDialog: false,
      showRegisterDialog: false,
      addressList: [],
      newAvatarFile: null,
      loginForm: {
        username: "",
        password: "",
        tenantId: 1,
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      registerForm: {
        name: "",
        phone: "",
        password: "",
        nickName: "",
        confirmPassword: "",
        address: "",
        avatar: null,
        avatarUrl: "",
        gender: "",
        email: "",
        introduction: "",
        gameHobby: "",
      },
      registerRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern:
              /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).*$/,
            message: "密码必须包含字母、数字和符号",
            trigger: "blur",
          },
          { min: 6, message: "密码长度至少6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: validateRegisterConfirmPassword,
            trigger: "blur",
            // 添加依赖字段，确保在密码字段变化时也触发确认密码验证
            dependencies: ["password"],
          },
        ],
        address: [{ required: true, message: "请选择地址", trigger: "change" }],
        avatarUrl: [
          { required: true, message: "请上传头像", trigger: "change" },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
      },
      userFormRules: {
        bossName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "姓名长度应在2-20个字符之间",
            trigger: "blur",
          },
        ],
        bossNickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "昵称长度应在2-20个字符之间",
            trigger: "blur",
          },
        ],
        bossEmail: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
        addressId: [
          { required: true, message: "请选择地址", trigger: "change" },
        ],
      },
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: "请输入原密码", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            pattern:
              /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).*$/,
            message: "密码必须包含字母、数字和符号",
            trigger: "blur",
          },
          { min: 6, message: "密码长度至少6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
      modifyPasswordDialogVisible: false,
    };
  },
  methods: {
    // 在 methods 中添加以下方法
    handlePlaymateAvatarChange(file) {
      this.playmateRegisterForm.playmateAvatar = file.raw;
      this.playmateRegisterForm.playmateAvatarUrl = URL.createObjectURL(
        file.raw
      );
      this.$nextTick(() => {
        this.$refs.playmateRegisterFormRef.validateField("playmateAvatarUrl");
      });
    },

    handlePlaymateRegisterSubmit() {
      this.$refs.playmateRegisterFormRef.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.append(
            "playmateNickname",
            this.playmateRegisterForm.playmateNickname
          );
          formData.append(
            "playmateGameHobby",
            this.playmateRegisterForm.playmateGameHobby
          );
          formData.append(
            "playmateDesc",
            this.playmateRegisterForm.playmateDesc
          );
          formData.append("tenantId", this.playmateRegisterForm.tenantId);
          formData.append("userId", this.user.id);

          if (this.playmateRegisterForm.playmateAvatar) {
            formData.append(
              "playmateAvatar",
              this.playmateRegisterForm.playmateAvatar
            );
          }
          // 调用注册陪玩的API
          bossApi
            .registerAsPlaymate(formData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("陪玩注册成功");
                this.playmateDialogFormVisible = false;
                // 可以选择重新加载用户身份信息
                this.getUserIdentity();
              } else {
                this.$message.error(res.message || "注册失败");
              }
            })
            .catch((err) => {
              console.error("陪玩注册失败", err);
              this.$message.error("网络错误，请重试");
            });
        } else {
          this.$message.error("请检查表单数据是否正确");
          return false;
        }
      });
    },
    openModifyPassword() {
      this.modifyPasswordDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.passwordFormRef.resetFields();
      });
    },
    cancelModifyPassword() {
      this.modifyPasswordDialogVisible = false;
      this.$refs.passwordFormRef.resetFields();
    },
    submitModifyPassword() {
      this.$refs.passwordFormRef.validate((valid) => {
        if (valid) {
          const passwordData = {
            id: this.user.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword,
            tenantId: this.loginForm.tenantId,
          };
          bossApi
            .modifyPassword(passwordData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("密码修改成功,请重新登录");
                this.modifyPasswordDialogVisible = false;
                this.user = {};
                localStorage.removeItem("user");
                localStorage.removeItem("token");
                localStorage.removeItem("currtPlaymate");
                this.$emit("logout");
              } else {
                this.$message.error(res.message || "密码修改失败");
              }
            })
            .catch((err) => {
              console.error("密码修改失败", err);
              this.$message.error("网络错误，请重试");
            });
        }
      });
    },
    handleAvatarChangeForUpdate(file) {
      this.newAvatarFile = file.raw;
      this.user.bossAvatar = URL.createObjectURL(file.raw);
    },
    onFormValidate(valid) {
      this.formValid = valid;
    },
    handleDropdownCommand(command) {
      switch (command) {
        case "giftBag":
          this.giftBagDialogVisible = true;
          break;
        case "consumptionRecord":
          this.$router.push("/boss/consumptionRecord");
          break;
        case "logout":
          this.logoutDialogVisible = true;
          break;
        case "wallet":
          this.$router.push("/boss/wallet");
          break;
        case "info":
          this.infoDialogFormVisible = true;
          break;
        case "modifyPassword":
          this.openModifyPassword();
          break;
          c;
      }
    },
    bossLogout() {
      this.logoutDialogVisible = false;
      bossApi.logout(this.user).then((res) => {
        if (res.code === 200) {
          this.$message.success("已退出登录");
          location.reload();
          this.user = {};
          localStorage.removeItem("user");
          localStorage.removeItem("token");
          localStorage.removeItem("currtPlaymate");
        } else {
          this.$message.error(res.message);
        }
      });
      this.showLoginDialog = true;
    },
    toggleUserDropdown() {
      this.showUserDropdown = !this.showUserDropdown;
    },
    // 注册
    handleAvatarChange(file) {
      this.registerForm.avatar = file.raw;
      this.registerForm.avatarUrl = URL.createObjectURL(file.raw);
      this.$nextTick(() => {
        this.$refs.registerForm.validateField("avatarUrl");
      });
    },

    handleRegisterSubmit() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.handleRegister();
        } else {
          this.$message.error("数据不符合要求，请检查！");
          return false;
        }
      });
    },
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          bossApi
            .login(this.loginForm)
            .then((res) => {
              if (res.code === 200) {
                // 1. 先保存用户信息
                localStorage.setItem("user", JSON.stringify(res.data));
                this.user = res.data;
                // 2. 调用 getIdentity，并等待其完成
                return bossApi.getUserIdentity(this.user); // 返回 Promise
              } else {
                this.$message.error(res.message || "登录失败");
                throw new Error(res.message);
              }
            })
            .then((identityRes) => {
              if (identityRes.code === 200) {
                this.currtPlaymate = identityRes.data;
                localStorage.setItem(
                  "currtPlaymate",
                  JSON.stringify(identityRes.data)
                );
              }
              // 3. 所有操作完成后，再刷新页面
              this.showLoginDialog = false;
              location.reload();
              this.$message.success("登录成功！");
            })
            .catch((err) => {
              this.$message.error("网络错误，请重试");
            });
        }
      });
    },
    handleRegister() {
      const formData = new FormData();
      formData.append("userTelephone", this.registerForm.phone);
      formData.append("userPassword1", this.registerForm.password);
      formData.append("userPassword2", this.registerForm.confirmPassword);
      formData.append("addressId", this.registerForm.address);
      formData.append("bossSex", this.registerForm.gender);
      formData.append("bossNickName", this.registerForm.nickName);
      formData.append("bossName", this.registerForm.name);
      formData.append("bossEmail", this.registerForm.email);
      formData.append("bossGameHobby", this.registerForm.gameHobby);
      formData.append("bossDesc", this.registerForm.introduction);
      formData.append("tenantId", this.loginForm.tenantId);

      if (this.registerForm.avatar) {
        formData.append("avatar", this.registerForm.avatar);
      }

      bossApi
        .register(formData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("注册成功，即将为您登录");
            localStorage.setItem("user", JSON.stringify(res.data));
            this.user = res.data;
            this.showRegisterDialog = false;
          } else {
            this.$message.error(res.message || "注册失败");
          }
        })
        .catch((err) => {
          console.error("注册接口调用失败", err);
          this.$message.error("网络错误，请重试");
        });
    },
    //点击跳转到陪玩页面
    openPlayHall() {
      console.log("对象" + this.currtPlaymate + "id" + this.currtPlaymate.id);
      if (this.currtPlaymate == null || this.currtPlaymate.id == null) {
        this.$message.error("您还不是大神，请先注册成为大神");
        this.playmateDialogFormVisible = true;
        return;
      }
      this.$router.push("/playmate/playPlayHall");
    },
    getUser() {
      const userStr = localStorage.getItem("user");
      this.user = userStr ? JSON.parse(userStr) : {};
    },
    handleCommand(command) {
      switch (command) {
        case "login":
          this.showLoginDialog = true;
          break;
        case "register":
          this.showRegisterDialog = true;
          break;
      }
    },
    getAllAddress() {
      bossApi.getAllAddress().then((res) => {
        this.addressList = res.data;
      });
    },
    updateUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.append("bossName", this.user.bossName);
          formData.append("bossNickname", this.user.bossNickname);
          formData.append("bossSex", this.user.bossSex);
          formData.append("addressId", this.user.addressId);
          formData.append("bossEmail", this.user.bossEmail);
          formData.append("bossDesc", this.user.bossDesc);
          formData.append("bossGameHobby", this.user.bossGameHobby);
          formData.append("tenantId", this.loginForm.tenantId);
          formData.append("id", this.user.id);
          if (this.newAvatarFile) {
            formData.append("bossAvatar", this.newAvatarFile);
          }
          bossApi
            .updateUser(formData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("更新成功");
                this.infoDialogFormVisible = false;
                localStorage.setItem("user", JSON.stringify(res.data));
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((error) => {
              console.error("更新失败", error);
              this.$message.error("更新失败，请重试");
            });
        } else {
          this.$message.error("请检查表单数据是否正确");
          return false;
        }
      });
    },
    //判断当前用户是否是陪玩
    getUserIdentity() {
      if (this.user != null) {
        bossApi.getUserIdentity(this.user).then((res) => {
          if (res.code === 200) {
            this.currtPlaymate = res.data;
            localStorage.setItem("currtPlaymate", JSON.stringify(res.data));
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    getAllGameType() {
      // 获取全部游戏类型
      bossApi
        .getAllGameType({
          tenantId: this.tenantId,
        })
        .then((res) => {
          if (res.code != 200) {
            this.$message.error(res.message);
            return;
          }
          console.log(res.data);
          this.games = res.data;
        });
    },
    //获取所有礼物类型记录
    getGifts() {
      bossApi
        .getGiftType({
          tenantId: this.tenantId,
        })
        .then((res) => {
          if (res.code == 200) {
            this.gifts = res.data;
          }
        });
    },
    //获取背包记录
    getUserBags() {
      bossApi
        .getUserBags({
          tenantId: this.tenantId,
          id: this.user.id,
        })
        .then((res) => {
          if (res.code === 200) {
            this.userBags = res.data;
            console.log(res.data);
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 获取礼物名称
    getGiftName(giftId) {
      console.log(this.gifts)
      const gift = this.gifts.find((g) => g.id === giftId);
      return gift ? gift.giftName : "未知礼物";
    },

    // 获取礼物图片
    getGiftImage(giftId) {
      const gift = this.gifts.find((g) => g.id === giftId);
      return gift ? gift.giftImg : "";
    },
  },
  created() {
    this.getUser();
    this.getAllAddress();
    this.getAllGameType();
    this.getGifts();
    const storedPlaymate = localStorage.getItem("currtPlaymate");
    if (storedPlaymate) {
      this.currtPlaymate = JSON.parse(storedPlaymate);
    }
    // 设置 userId
    if (this.user && this.user.id) {
      this.playmateRegisterForm.userId = this.user.id;
    }
    this.getUserBags();
  },
  watch: {
    // 监听用户变化，当用户登录后获取背包数据
    user: {
      handler(newVal) {
        if (newVal && newVal.id) {
          this.getUserBags();
        }
      },
      immediate: true,
    },
  },
};
</script>

<style scoped>
.gift-bag-dialog >>> .el-dialog__body {
  padding: 20px;
}

.gift-bag-container {
  min-height: 300px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #999;
  font-size: 16px;
}

.gift-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.gift-item {
  text-align: center;
}

.gift-image-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 auto 10px;
}

.gift-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
}

.gift-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #ff4d4d;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.gift-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.password-form {
  padding: 20px 0;
}

.password-form .el-form-item {
  margin-bottom: 20px;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}
.user-basic-info {
  padding: 12px 16px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}

.user-basic-info p {
  margin: 4px 0;
}
.user-avatar-container {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: color 0.3s;
  padding: 5px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-nickname {
  font-size: 14px;
  color: #333;
}

.el-dropdown-link {
  cursor: pointer;
  color: #333;
  font-size: 14px;
}

.el-dropdown-link:hover {
  color: #ff4d4d;
}
.compact-form {
  padding: 20px;
}

.compact-form-item {
  margin-bottom: 12px;
}

.compact-form-item .el-form-item__label {
  font-size: 13px;
  padding: 0;
}

.compact-form-item .el-form-item__content {
  margin-left: 0;
}

.compact-form-item .el-input,
.compact-form-item .el-select {
  width: 100%;
}

.compact-form-item .el-input__inner,
.compact-form-item .el-select__trigger {
  height: 32px;
  font-size: 13px;
  border-radius: 4px;
}

.compact-form-item .el-upload {
  width: 100%;
}

.compact-form-item .avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.compact-form-item .avatar-uploader-icon {
  font-size: 18px;
  color: #999;
}
.user-dropdown {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  color: #333;
  font-size: 14px;
}

.el-dropdown-link:hover {
  color: #ff4d4d;
}

.dropdown-item-link {
  text-decoration: none;
  color: inherit;
  display: block;
  width: 100%;
}
.aside-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #eee;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo-img {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.logo-text {
  text-align: left;
}

.logo-text h1 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.logo-text p {
  font-size: 12px;
  color: #666;
  margin: 5px 0 0;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.menu-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 30px;
}

.menu-item {
  position: relative;
}

.menu-link {
  color: #333;
  text-decoration: none;
  font-size: 16px;
  padding: 5px 0;
  transition: color 0.3s;
}

.menu-link:hover {
  color: #ff4d4d;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
}

.search-input {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  width: 200px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #ff4d4d;
}

.search-btn {
  background-color: transparent;
  border: none;
  cursor: pointer;
  padding: 8px;
  color: #999;
}

.icon-search {
  font-size: 16px;
}

.user-actions {
  display: flex;
  gap: 20px;
  align-items: center;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: color 0.3s;
}

.action-item:hover {
  color: #ff4d4d;
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
}

.icon {
  font-size: 18px;
}

.action-text {
  font-size: 14px;
  color: #333;
}
</style>
